#!/bin/bash

# This script reads all DICOM series in a directory
# and writes them to multiple .mhd's.

#############################################################################

# Argument parsing
if [ "$#" -gt "8" ] || [ "$#" -lt "4" ] || [ "$1" == "--help" ]
then
	echo "Usage: pxgetAllDICOMseries"
  echo " -i    dicomDirectoryName"
	echo " -o    outputbasename"
	echo " [-p]  outputPixelComponentType"
	echo " [-r]  restrictions"
	exit 1
fi

while getopts "i:o:p:r:" argje
do
	case $argje in
		i ) dicomDir="$OPTARG";;
		o ) outbase="$OPTARG";;
		p ) opct="$OPTARG";;
		r ) res="$OPTARG";;
		* ) echo "ERROR: Wrong arguments"; exit 1;;
	esac
done

if [ "$dicomDir" == "" ]
then
	echo "ERROR: -i is required"; exit 1;
fi
if [ "$outbase" == "" ]
then
	echo "ERROR: -o is required"; exit 1;
fi

# Get a list of all series in this directory
if [[ $res == "" ]]
then
	serieslist=`pxgetDICOMseriesUIDs -in $dicomDir | dos2unix`
else
	serieslist=`pxgetDICOMseriesUIDs -in $dicomDir -r $res | dos2unix`
fi

# Check if not an empty list
if [ "$serieslist" == "" ]
then
	exit 1;
fi

# Loop over the series
i=1
for series in $serieslist
do
	# Create a number
	number=`printf "%03d" $i`

	# Create an outputname
	out=$outbase$number".mhd"

	# Get the arguments
	args="-in "$dicomDir" -out "$out" -s $series"
	if [ "$opct" != "" ]; then args=$args" -opct "$opct; fi
	if [ "$res"  != "" ]; then args=$args" -r "$res; fi

	# Get the DICOM series and write to $out
	pxcastconvert $args

	# Increase iteration number
	let "i += 1"
	echo "--------------------------------------------------"

done

# exit the script
exit 0

